package com.gopay.scheduler.job;

import com.gopay.common.constants.fund.FundOrderTypeEnum;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.OrderLifecycleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jianghp
 * @description 清理基金活期宝转入超时订单
 * @date 2017/12/19 10:03
 * Copyright (c) 2017. www.gopay.com.cn Inc.All rights reserved.
 */
public class FundOrdersTimeoutCleanJob extends GopayBaseJob {
    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(FundOrdersTimeoutCleanJob.class);

    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;
    private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;

    @Resource(name = "cpsGeneralMainOrderOperClient")
    public void setCpsGeneralMainOrderOperClient(
            MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient) {
        this.cpsGeneralMainOrderOperClient = cpsGeneralMainOrderOperClient;
    }

    @Resource(name = "cpsGeneralMainOrderDAO")
    public void setCpsGeneralMainOrderDAO(
            CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO) {
        this.cpsGeneralMainOrderDAO = cpsGeneralMainOrderDAO;
    }

    @Override
    public void doJobInternal() {
        LOGGER.info("【清理基金转入超时订单】开始");
        Map param = new HashMap();
        String B2cName = "02019" + OrderLifecycleUtil.B2C;
        String b2c = OrderLifecycleUtil.getLifecycle(B2cName);
        param.put("b2c", b2c);

        int count = cpsGeneralMainOrderDAO.findTimeoutOrdersInFundCount(param);
        LOGGER.info("【清理基金转入超时订单】获取到的超时订单数量为：{}", count);
        if (count == 0) {
            LOGGER.info("【清理基金转入超时订单】未获取到超时订单，任务结束！");
            return;
        }
        //循环次数
        int i = (count + 999) / 1000;
        for (int j = 0; j < i; j++) {
            //每次1000条
            List<Object> orderList = cpsGeneralMainOrderDAO.findTimeoutOrdersInFund(param, j * 1000 + 1, 1000);
            updateStatus(orderList);
        }
        LOGGER.info("【清理基金转入超时订单】结束");

    }

    /**
     * 批量修改订单状态
     * @author yhwpeng@126.com
     * @date 2018-02-05 11:22:07
     * @params
     * @param orderList :
     * @return void
     */
    private void updateStatus(List<Object> orderList) {
        if (!(orderList.isEmpty())) {
            String txnStaCode = String.valueOf(TxnStaCode.TXN_STA_CD_20002.value);
            LOGGER.info("【清理基金转入超时订单】本次需要处理的超时订单共：{}条，明细：{}", orderList.size(), orderList.toString());
            LOGGER.info("【清理基金转入超时订单】Overtime timeout order clean-up work now!");
            Map<MainOrderField, String> map = new HashMap<MainOrderField, String>();

            map.put(MainOrderField.TXN_STA_CD, txnStaCode);
            SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
            map.put(MainOrderField.TRAN_FINISH_TIME, sf.format(new Date()));
            String orderType = FundOrderTypeEnum.PAY_FAILURE.getValue();
            for (Object obj : orderList) {
                String gopayOrderId = String.valueOf(obj);
                try {
                    cpsGeneralMainOrderOperClient.updateMainAndFundOrder(gopayOrderId, map, orderType);
                } catch (GopayException e) {
                    LOGGER.error("【清理基金转入超时订单】修改订单状态异常，订单号：{}", gopayOrderId, e);
                } catch (Exception e) {
                    LOGGER.error("【清理基金转入超时订单】修改订单状态发生未知异常，订单号：{}", gopayOrderId, e);
                }
            }
        }
    }
}
